package com.pmcc.yn.service;

import com.pmcc.utils.*;
import com.pmcc.yn.entity.*;
import com.pmcc.yn.repository.*;
import com.pmcc.yn.vo.OrderListVo;
import com.pmcc.yn.vo.OrderVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.persistence.criteria.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.Timestamp;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by xuwanlin on 2019/1/11.
 */
@Service
@Transactional
public class OrderListService {

    @Autowired
    OrderListRepository repository;
    @Autowired
    StoreInfoRepository storeInfoRepository;
    @Autowired
    AcceptInfoRepository acceptInfoRepository;
    @Autowired
    EvaluateInfoRepository evaluateInfoRepository;
    @Autowired
    TechnicianInfoRepository technicianInfoRepository;
    @Autowired
    EntryInfoRepository entryInfoRepository;
    @Value("${web.downloadFile}")
    private static String downloadFile;

    public ResultBean showList(AntdPage antdPage, OrderList model) throws Exception {
        ResultBean resultBean = new ResultBean();
        Page page = repository.findAll(this.getSpecification(model), antdPage.getPageRequest());

        resultBean.setPage(antdPage.getDefaultCurrent());
        resultBean.setTotal(page.getTotalElements());
        resultBean.setResultCode(ResultBean.SUCCESS);
        resultBean.setPageSize(antdPage.getPageSize());
        resultBean.setRows(page.getContent());
        return resultBean;
    }

    public Specification<OrderList> getSpecification(OrderList model) {
        return new Specification<OrderList>() {
            @Override
            public Predicate toPredicate(Root<OrderList> root, CriteriaQuery<?> query, CriteriaBuilder builder) {
                List<Predicate> list = new ArrayList<Predicate>();
                if (model.getDelFlag() != null) {
                    list.add(builder.equal(root.get("delFlag").as(Integer.class), model.getDelFlag()));
                }

                if (model.getFlag() != null) {
                    list.add(builder.equal(root.get("flag").as(Integer.class), model.getFlag()));
                }

                Predicate[] p = new Predicate[list.size()];
                query.orderBy(builder.desc(root.get("createTime")));
                return builder.and(list.toArray(p));
            }
        };
    }

    /**
     * 新增
     *
     * @return
     */
    public ResultBean add(OrderList model) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            model.setCreateTime(new Date());
            model.setDelFlag(0);
            model.setFlag(0);
            repository.saveAndFlush(model);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setResultDesc("新增成功");
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }


    /**
     * 修改
     *
     * @param map
     * @return
     */
    public ResultBean update(Map map) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            OrderList c = repository.findById(map.get("id").toString());
            BeanUtils.setBeanData(c, map);
            repository.saveAndFlush(c);
            resultBean.setResultCode(ResultBean.SUCCESS);
            resultBean.setObject(c);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public ResultBean deleteById(String id, String orderid) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            repository.delete(id);
//            OrderList f = repository.findById(id);
//            f.setDelFlag(1);
//            OrderList c=repository.saveAndFlush(f);
            resultBean.setResultCode(ResultBean.SUCCESS);
//            resultBean.setObject(c);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }


    //评分照片上传
    public String scorePhoto(MultipartFile file, String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        // 上传的文件存放路径
        String uploadDiskPath = downloadFile;
        String employeeID;
        if (!file.isEmpty()) {
            try {
                String originalFilename = new String(file.getOriginalFilename());
                String[] arr = originalFilename.split("\\.");
                // 文件类型
                String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
                // 存放在服务器端的文件名
                String serverFileName = fileType == "" ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;
                // 创建文件夹  年-月-日/goods
                String folder = "/" + DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
                // 数据库存放路径：年-月-日/文件名
                String fileUrl = "/" + folder + "/" + serverFileName;

                OrderList c = repository.findById(id);
//                c.setPhoto("/downloadFile"+fileUrl);
                repository.saveAndFlush(c);
                File targetFile = new File(uploadDiskPath, fileUrl);
                if (!targetFile.exists()) {
                    targetFile.getParentFile().mkdir();
                    targetFile.createNewFile();
                }
                file.transferTo(targetFile);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
                return "上传失败," + e.getMessage();
            }
            return "上传成功";
        } else {
            return "上传失败，因为文件是空的.";
        }
    }

    //查询技师列表
    public ResultBean personList(String orderid) {

        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
//            List<Order> list = repository.personList(orderid);
            resultBean.setResultCode(ResultBean.SUCCESS);
//            resultBean.setRows(list);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }


    public OrderList queryOrderDetail(String id) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        OrderList orderList = new OrderList();
        orderList = repository.getOne(id);
        if (orderList != null) {
            StoreInfo storeInfo = storeInfoRepository.getOne(orderList.getStoreId());
            orderList.setStoreAddress(storeInfo.getProvence() + "-" + storeInfo.getCity() + "-" + storeInfo.getArea() + "-" + storeInfo.getAddress());
            orderList.setStoreName(storeInfo.getName());
        }
        return orderList;
    }

    /**
     * 确认合作
     */
    public ResultBean techAccept(String id, String orderId) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            AcceptInfo acceptInfo = acceptInfoRepository.findByTechIdAndOrderId(id,orderId);
            acceptInfo.setFlag(1);
            acceptInfoRepository.saveAndFlush(acceptInfo);
            OrderList orderList = repository.findById(orderId);
            orderList.setFlag(2);
            repository.saveAndFlush(orderList);
            resultBean.setResultCode(ResultBean.SUCCESS);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    /**
     * 追加赏金
     */
    public ResultBean updateMoneyById(String id, String money) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            OrderList orderList = repository.findById(id);
            orderList.setMoney(orderList.getMoney() + Double.parseDouble(money));
            repository.saveAndFlush(orderList);
            resultBean.setObject(orderList);
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //门店订单待评价
    public ResultBean storeOrderByFlag(String id, String flag) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<OrderList> orderList = repository.findByStoreId(id);
            List<OrderListVo> list = new ArrayList<>();
            for (OrderList orderList1 : orderList) {
                if (flag.equals(orderList1.getFlag())) {
                    OrderListVo orderListVo = new OrderListVo();
                    orderListVo.setPreTime(orderList1.getPreTime());
                    orderListVo.setSerType(orderList1.getSerType());
                    orderListVo.setMoney(orderList1.getMoney());
                    TechnicianInfo technicianInfo = technicianInfoRepository.findById(orderList1.getTechId());
                    //orderListVo.setTechName(technicianInfo.getName());
                    orderListVo.setTechName(technicianInfo.getName());
                    list.add(orderListVo);

                }
                resultBean.setRows(list);

            }
        } catch (Exception e) {
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    //发布订单
    public ResultBean addOrder(OrderList orderList, MultipartFile file) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            orderList.setCreateTime(new Date());
            orderList.setVehPicl(this.orderPhoto(file));
            repository.saveAndFlush(orderList);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

//订单图片上传
public String orderPhoto(MultipartFile file) {
    ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
    // 上传的文件存放路径
    String uploadDiskPath = downloadFile;
    String employeeID;
    if (!file.isEmpty()) {
        try {
            String originalFilename = new String(file.getOriginalFilename());
            String[] arr = originalFilename.split("\\.");
            // 文件类型
            String fileType = arr.length > 1 ? arr[arr.length - 1] : "";
            // 存放在服务器端的文件名
            String serverFileName = fileType == "" ? UUIDGenerator.getUUID() : UUIDGenerator.getUUID() + "." + fileType;
            // 创建文件夹  年-月-日/goods
            String folder = "/" + DateUtil.DateToString(new Timestamp(new Date().getTime()), "yyyy-MM-dd");
            // 数据库存放路径：年-月-日/文件名
            String fileUrl = "/" + folder + "/" + serverFileName;

//            OrderList c = repository.findById(id);
////                c.setPhoto("/downloadFile"+fileUrl);
//            repository.saveAndFlush(c);
            File targetFile = new File(uploadDiskPath, fileUrl);
            if (!targetFile.exists()) {
                targetFile.getParentFile().mkdir();
                targetFile.createNewFile();
            }
            file.transferTo(targetFile);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        } catch (IOException e) {
            e.printStackTrace();
            return "上传失败," + e.getMessage();
        }
        return "上传成功";
    } else {
        return "上传失败，因为文件是空的.";
    }

    public ResultBean orderShow(String message,String xx,String yy) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            //获得orderList集合
            List<OrderList> list = repository.findAllBySerTypeLikeOrStoreNameLike(message);
            List<OrderVo> listVo = new ArrayList<>();
            for (OrderList orderList:list){
                OrderVo vo = new OrderVo();
                //订单id
                vo.setId(orderList.getId());
                //汽车图片1
                vo.setVehPic1(orderList.getVehPicl());
                //汽车图片2
                vo.setVehPic2(orderList.getVehPic2());
                //汽车图片3
                vo.setVehPic3(orderList.getVehPic3());
                //赏金
                vo.setMoney(orderList.getMoney());
                //订单地址
                vo.setOrderAddress(orderList.getOrderAddress());
                //任务时间
                vo.setPreTime(orderList.getPreTime());
                //门店名称
                vo.setStoreName(orderList.getStoreName());
                //服务类型
                vo.setSerType(orderList.getSerType());
                List<EntryInfo> entryInfoList = entryInfoRepository.findByOrderId(orderList.getId());
                //报名人数
                vo.setEntryNum(entryInfoList.size());
                StoreInfo storeInfo = storeInfoRepository.findById(orderList.getStoreId());
                //距离
                vo.setDistance(TranslateUtil.getDistance(Double.parseDouble(xx),Double.parseDouble(yy),Double.parseDouble(storeInfo.getXx()),Double.parseDouble(storeInfo.getYy())));
                listVo.add(vo);
            }
            resultBean.setRows(listVo);
        }catch (Exception e){
            resultBean.setResultCode(ResultBean.FAIL);
        }
        return resultBean;
    }

    public ResultBean orderById(String id,String xx,String yy) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            OrderList orderList = repository.findById(id);
            OrderVo vo = new OrderVo();
            //订单id
            vo.setId(id);
            //汽车图片1
            vo.setVehPic1(orderList.getVehPicl());
            //汽车图片2
            vo.setVehPic2(orderList.getVehPic2());
            //汽车图片3
            vo.setVehPic3(orderList.getVehPic3());
            //赏金
            vo.setMoney(orderList.getMoney());
            //订单地址
            vo.setOrderAddress(orderList.getOrderAddress());
            //任务时间
            vo.setPreTime(orderList.getPreTime());
            //门店名称
            vo.setStoreName(orderList.getStoreName());
            //服务类型
            vo.setSerType(orderList.getSerType());
            //详细内容
            vo.setDetRequirement(orderList.getDetRequirement());
            List<EntryInfo> entryInfoList = entryInfoRepository.findByOrderId(orderList.getId());
            //报名人数
            vo.setEntryNum(entryInfoList.size());
            StoreInfo storeInfo = storeInfoRepository.findById(orderList.getStoreId());
            //联系电话
            vo.setTel(storeInfo.getPhone());
            //距离
            vo.setDistance(TranslateUtil.getDistance(Double.parseDouble(xx),Double.parseDouble(yy),Double.parseDouble(storeInfo.getXx()),Double.parseDouble(storeInfo.getYy())));
            resultBean.setObject(vo);

        }catch (Exception e){

        }
        return resultBean;
    }

    public ResultBean recommend(String type,String xx,String yy) {
        ResultBean resultBean = new ResultBean(ResultBean.SUCCESS);
        try {
            List<OrderList> list = repository.findBySerType(type);
            OrderList orderList = list.get(0);
            OrderVo vo = new OrderVo();
            //订单id
            vo.setId(orderList.getId());
            //服务类型
            vo.setSerType(orderList.getSerType());
            //汽车图片1
            vo.setVehPic1(orderList.getVehPicl());
            //汽车图片2
            vo.setVehPic2(orderList.getVehPic2());
            //汽车图片3
            vo.setVehPic3(orderList.getVehPic3());
            //门店名称
            vo.setStoreName(orderList.getStoreName());
            //赏金
            vo.setMoney(orderList.getMoney());
            //订单地址
            vo.setOrderAddress(orderList.getOrderAddress());
            List<EntryInfo> entryInfoList = entryInfoRepository.findByOrderId(orderList.getId());
            //报名人数
            vo.setEntryNum(entryInfoList.size());
            StoreInfo storeInfo = storeInfoRepository.findById(orderList.getStoreId());
            //距离
            vo.setDistance(TranslateUtil.getDistance(Double.parseDouble(xx),Double.parseDouble(yy),Double.parseDouble(storeInfo.getXx()),Double.parseDouble(storeInfo.getYy())));
            resultBean.setObject(vo);
        }catch (Exception e){
            resultBean.setResultDesc(ResultBean.FAIL);
        }
        return resultBean;
    }

}

}




